package org.sample.springbootasync.web;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.concurrent.Future;

import org.sample.springbootasync.service.DateTimeService;
import org.sample.springbootcommon.model.DateTimeRequest;
import org.sample.springbootcommon.model.DateTimeResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
@EnableAutoConfiguration
@RequestMapping("/task")
public class AsyncTaskController {

	private static final Logger LOGGER = LoggerFactory.getLogger(AsyncTaskController.class);

	@Autowired
	private DateTimeService service;

	@GetMapping("/run")
	public List<String> run(@RequestParam int count) {

		Date startTime = new Date();

		List<Future<DateTimeResponse>> futures = new ArrayList<>(count);
		for (int i = 0; i < count; i++) {
			DateTimeRequest request = new DateTimeRequest();
			request.setId(Integer.toString(i));
			futures.add(service.asyncPost(request));
		}

		List<String> results = new ArrayList<>(count);
		for (int i = 0; i < count; i++) {
			String result = "";
			try {
				DateTimeResponse response = futures.get(i).get();
				result = String.format("%2d: %s - %s", i, response.getStart(), response.getEnd());
			} catch (Exception ex) {
				LOGGER.error("Get result failed", ex);
			}
			results.add(result);
		}

		Date endTime = new Date();
		LOGGER.info("Elapsed time: {}s", (endTime.getTime() - startTime.getTime()) / 1000);

		return results;
	}
	
	@PostMapping("/run")
	public List<String> runPost(@RequestBody String requestBody) {
		
		return Collections.emptyList();
	}

}
